<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="取车门店名称" prop="takeStoreName">
          <el-input
            v-model="queryParams.takeStoreName"
            placeholder="请输入取车门店名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="还车门店名称" prop="alsoStoreName">
          <el-input
            v-model="queryParams.alsoStoreName"
            placeholder="请输入还车门店名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="isAvailable">
          <el-select v-model="queryParams.isAvailable">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="未启用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="custom_card">
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            class="first-plain-btn"
            size="medium"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['plan:fee:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            class="sec-plain-btn"
            size="medium"
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['plan:fee:remove']"
            >删除</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="feeList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="取车门店名称"
          align="center"
          prop="takeStoreName"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="还车门店名称"
          align="center"
          prop="alsoStoreName"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="费用"
          align="center"
          prop="totalPrice"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          min-width="160"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="租户"
          align="center"
          prop="tenantName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="是否启用"
          align="center"
          min-width="120"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_available"
              :value="scope.row.isAvailable"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="left"
          width="180"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['plan:items:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['plan:items:remove']"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleAvailable(scope.row, 1)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['store:store:edit']"
              >启用</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleAvailable(scope.row, 0)"
              v-if="scope.row.isAvailable == 1"
              v-hasPermi="['store:store:edit']"
              >停用</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改异地还车费对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="取车门店" prop="takeStoreName">
              <el-select
                v-model="form.takeStoreName"
                @change="takeChange"
                style="width: 100%"
              >
                <template v-for="item in storeList">
                  <el-option
                    :key="item.storeId"
                    :label="item.storeName"
                    :value="item.storeId"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="还车门店" prop="alsoStoreName">
              <el-select
                v-model="form.alsoStoreName"
                @change="alsoChange"
                style="width: 100%"
              >
                <template v-for="item in storeList">
                  <el-option
                    :key="item.storeId"
                    :label="item.storeName"
                    :value="item.storeId"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isAvailable">
              <el-switch
                class="mySwitch"
                v-model="form.isAvailable"
                active-text="启用"
                inactive-text="禁用"
                active-value='1'
                inactive-value='0'
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用" prop="totalPrice">
              <el-input
                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                maxlength="12"
                v-model.trim="form.totalPrice"
                placeholder="请输入费用"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-col-12 {
  height: 58px;
}
</style>
<style lang="scss">
.mySwitch {
  margin-left: -50px;
  .el-switch__label--left {
    position: relative;
    left: 75px;
    color: #fff;
    z-index: -1111;
    span {
      width: 40px;
    }
  }
  .el-switch__label--right {
    position: relative;
    right: 65px;
    color: #fff;
    z-index: -1111;
    span {
      display: inline-block;
      width: 40px;
    }
  }
  .el-switch__core {
    width: 65px !important;
  }
  .el-switch__label--right.is-active {
    z-index: 10;
    color: #fff !important;
  }
  .el-switch__label--left.is-active {
    z-index: 10;
    color: #fff !important;
  }
  .el-switch__core {
    height: 24px !important;
    border-radius: 12px !important;
  }
  .el-switch__core:after {
    top: 3px;
    left: 5px;
  }
  .el-switch.is-checked .el-switch__core::after {
    margin-left: -20px;
  }
}
</style>

<script>
import {
  listFee,
  getFee,
  delFee,
  addFee,
  updateFee,
  exportFee,
  storeList,
  calculateDistance,
  stopUsingEnabled,
} from "@/api/plan/fee";

export default {
  name: "Fee",
  dicts: ["store_type", "sys_available", "store_class", "service_mode"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 异地还车费表格数据
      feeList: [],
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        takeStoreId: null,
        takeStoreName: null,
        alsoStoreId: null,
        alsoStoreName: null,
        distance: null,
        totalPrice: null,
        unitPrice: null,
        isAvailable: null,
        deptId: null,
        tenantId: null,
      },
      // 表单参数
      form: {
        isAvailable: "1",
      },
      // 表单校验
      rules: {
        takeStoreName: [{ required: true, message: "请输入取车门店" }],
        alsoStoreName: [{ required: true, message: "请输入还车门店" }],
        totalPrice: [
          { required: true, message: "请输入费用" },
          {
            pattern: /^[0-9]+(.[0-9]{1,2})?$/,
            message: "价值为正数，且保留两位小数",
            trigger: "blur",
          },
          {
            pattern: /^([1-9]\d{0,8}|0)(\.\d{1,2})?$/,
            message: "费用不能大于999999999.99",
            trigger: "blur",
          },
          {
            pattern: /^(?!0+(?:\.0+)?$)([1-9]\d*|0)(?:\.\d{1,2})?$/,
            message: "费用不能为0",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getStoreList();
  },
  methods: {
    /* 门店 */
    async getStoreList() {
      const result = await storeList();
      this.storeList = result.rows || [];
      storeList().then((response) => {
        this.storeList = response.data;
      });
    },
    calculateDistance() {
      if (this.form.alsoStoreId == null || this.form.takeStoreId == null) {
        alert("请选择门店");
        return;
      }
    },
    takeChange(val) {
      this.form.takeStoreId = val;
      this.storeList.map((item) => {
        if (val == item.storeId) {
          this.form.takeStoreName = item.storeName;
        }
      });
    },
    alsoChange(val) {
      this.form.alsoStoreId = val;
      this.storeList.map((item) => {
        if (val == item.storeId) {
          this.form.alsoStoreName = item.storeName;
        }
      });
    },
    /** 查询异地还车费列表 */
    getList() {
      this.loading = true;
      listFee(this.queryParams).then((response) => {
        this.feeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        alsoFeeId: null,
        takeStoreId: null,
        takeStoreName: null,
        alsoStoreId: null,
        alsoStoreName: null,
        distance: null,
        totalPrice: null,
        unitPrice: null,
        delFlag: null,
        isAvailable: "1",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: null,
        tenantId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.alsoFeeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加异地还车费";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const alsoFeeId = row.alsoFeeId || this.ids;
      getFee(alsoFeeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改异地还车费";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (valid) {

          if (this.form.takeStoreId === this.form.alsoStoreId) {
            this.$message({
              message: '取车门店不能与还车门店相同，请重新选择门店',
              type: 'warning'
            });
            return
          }

          if (this.form.alsoFeeId != null) {
            updateFee(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFee({...this.form,distance:1,unitPrice:this.form.totalPrice,}).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 启用/停用 */
    handleAvailable(row, available) {
      stopUsingEnabled({
        alsoFeeId: row.alsoFeeId,
        isAvailable: available,
      }).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const alsoFeeIds = row.alsoFeeId || this.ids;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delFee(alsoFeeIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有异地还车费数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportFee(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
